package com.midea.oms.Demo;

import javax.websocket.ClientEndpoint;
import javax.websocket.CloseReason;
import javax.websocket.ContainerProvider;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
import java.net.URI;
import java.util.Scanner;

@ClientEndpoint
public class MyClientEndpoint {
    private Session session;
    private String username;

    @OnOpen
    public void onOpen(Session session) {
        System.out.println("WebSocket connection opened: " + session.getId());
        this.session = session;
    }

    @OnClose
    public void onClose(Session session, CloseReason reason) {
        System.out.println("WebSocket connection closed: " + reason.getReasonPhrase());
        this.session = null;
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        throwable.printStackTrace();
    }

    @OnMessage
    public void onMessage(String message) {
        System.out.println("Received message: " + message);
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void sendMessage(String targetUsername, String message) {
        try {
            session.getBasicRemote().sendText(targetUsername + ":" + message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        try {
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            MyClientEndpoint client1 = new MyClientEndpoint();
            client1.setUsername("user1");
            container.connectToServer(client1, new URI("ws://localhost:8080/myHandler"));


            Scanner scanner = new Scanner(System.in);
            while (true) {
                System.out.print("Enter message: ");
                String message = scanner.nextLine();
                if (message.equalsIgnoreCase("quit")) {
                    break;
                }
                client1.sendMessage("user2", message);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}